package net.sf.midollo.io.log;

import net.sf.midollo.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class LogInputStream extends InputStream {

	protected final InputStream is;
	protected final OutputStream log;

	public LogInputStream(InputStream is, OutputStream log) {
		if (is == null)
			is = IOUtils.NULL_INPUT;
		if (log == null)
			log = IOUtils.NULL_OUTPUT;
		this.is = is;
		this.log = log;
	}

	public int read() throws IOException {
		int c = this.is.read();
		if (c >= 0)
			this.log.write(c);
		return c;
	}

	public int read(byte[] b) throws IOException {
		int nread = this.is.read(b);
		if (nread >= 0)
			this.log.write(b, 0, nread);
		return nread;
	}

	public int read(byte[] b, int off, int len) throws IOException {
		int nread = this.is.read(b, off, len);
		if (nread >= 0)
			this.log.write(b, off, nread);
		return nread;
	}

	public long skip(long n) throws IOException {
		return this.is.skip(n);
	}

	public int available() throws IOException {
		return this.is.available();
	}

	public void close() throws IOException {
		try {
			this.is.close();
		} finally {
			this.log.close();
		}
	}

	public void mark(int readlimit) {
		this.is.mark(readlimit);
	}

	public void reset() throws IOException {
		this.is.reset();
	}

	public boolean markSupported() {
		return this.is.markSupported();
	}
}
